package com.hzit.pay.web.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * rabbitMq的配置
 */
@Configuration
public class RabbitMqConfig {


    //业务交换机
    public static final String BUSINESS_EXCHANGE_NAME = "pay_biz_exchange";

    //支付回调队列
    public static final String BUSINESS_QUEUEA_NAME = "pay_notify_queue";


    //死信交换机
    public static final String DEAD_LETTER_EXCHANGE = "pay_dead_exchange";

    //死信队列
    public static final String DEAD_LETTER_QUEUEA_NAME = "pay_dead_queue";


    //业务队列A的死信路由key
    public static final String DEAD_LETTER_QUEUEA_ROUTING_KEY = "pay_dead_queue_key";


    /**
     * 声明业务Exchange
     * @return
     */
    @Bean("businessExchange")
    public FanoutExchange businessExchange(){
        return new FanoutExchange(BUSINESS_EXCHANGE_NAME);
    }

    /**
     * 声明死信Exchange
     * @return
     */
    @Bean("deadLetterExchange")
    public DirectExchange deadLetterExchange(){
        return new DirectExchange(DEAD_LETTER_EXCHANGE);
    }


    // 声明业务队列A
    @Bean("bizQueueA")
    public Queue businessQueueA(){
        Map<String, Object> args = new HashMap<>(2);


//       x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
//       x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", DEAD_LETTER_QUEUEA_ROUTING_KEY);


        //设置队列的ttl， 队列中的消息存活时间就是10秒
        args.put("x-message-ttl",1000);


        return QueueBuilder.durable(BUSINESS_QUEUEA_NAME).withArguments(args).build();
    }




    // 声明死信队列A
    @Bean("deadLetterQueueA")
    public Queue deadLetterQueueA(){
        return new Queue(DEAD_LETTER_QUEUEA_NAME);
    }



    // 声明业务队列A绑定关系
    @Bean
    public Binding businessBindingA(@Qualifier("bizQueueA") Queue queue,
                                    @Qualifier("businessExchange") FanoutExchange exchange){
        return BindingBuilder.bind(queue).to(exchange);
    }


    // 声明死信队列A绑定关系
    @Bean
    public Binding deadLetterBindingA(@Qualifier("deadLetterQueueA") Queue queue,
                                      @Qualifier("deadLetterExchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(DEAD_LETTER_QUEUEA_ROUTING_KEY);
    }




}
